#include "crane_watch_keypad.h"

#if USE_CRANE_WATCH_KEYPAD

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "../../board.h"
#include "lvgl/src/lv_hal/lv_hal_tick.h"
#include "lvgl/src/lv_core/lv_group.h"
#include "ft6x36.h"
#include "zinitix.h"
#include "crane_onkey.h"

static keypad_cb_t user_cb;

static void handle_vk(struct keypad_param *val)
{
    static int last_vk_state = LV_INDEV_STATE_REL;
    static uint32_t press_start_time = 0;
    static uint8_t long_pressed = 0;

#if USE_FT6X36
    ft6x36_vk_read(&val->data);
#elif USE_ZINITIX_TOUCH
    zinitix_vk_read(&val->data);
#else
    val->data.state = LV_INDEV_STATE_REL;
#endif

    val->key_event = KEY_EVENT_NONE;
    if((last_vk_state == LV_INDEV_STATE_REL) && (val->data.state == LV_INDEV_STATE_PR)) {
        press_start_time = lv_tick_get();
        long_pressed = 0;
    } else if((last_vk_state == LV_INDEV_STATE_PR) && (val->data.state == LV_INDEV_STATE_PR)) {
        if((long_pressed == 0) &&lv_tick_elaps(press_start_time)>KEY_LONG_PRESS_DURATION) {
            long_pressed = 1;
            val->key_event = KEY_EVENT_LONG_PRESS;
        }
    } else if((last_vk_state == LV_INDEV_STATE_PR) && (val->data.state == LV_INDEV_STATE_REL)) {
        if(long_pressed == 0) {
            val->key_event = KEY_EVENT_CLICK;
        } else {
            val->key_event = KEY_EVENT_RELEASE;
        }

        long_pressed = 0;
    }
    last_vk_state = val->data.state;
}

bool keypad_watch_read(lv_indev_drv_t *indev_drv, lv_indev_data_t *data)
{
    (void) indev_drv;      /*Unused*/

    struct keypad_param val;
#if USE_ONKEY_HISR
    handle_onkey(&val);
#endif
    if((val.key_event == KEY_EVENT_NONE) && (val.data.state == LV_INDEV_STATE_REL)) {
        handle_vk(&val);
    }

    if(user_cb) {
        user_cb(&val);
    }

    *data = val.data;
    return false;
}


void keypad_watch_init(keypad_cb_t cb)
{
    user_cb = cb;
#if USE_ONKEY_HISR
    onkey_init();
    lv_pm_info_t pm_info;
    pm_info.suspend = onkey_suspend;
    pm_info.resume = onkey_resume;
    pm_info.data = NULL;
    pm_info.part = LV_PM_PART_MISC;
    lv_pm_register(&pm_info);
#endif
}

#endif /* USE_CRANE_WATCH_KEYPAD */
